var qcloud = require('../../../vendor/sdk/index');
var config = require('../../../config');
var app = getApp();

Page({
  data: {
    navH: app.globalData.navHeight,
    userInfo: null,
    fileHost: app.globalData.imageUrl,
    formItems: [
      {
        label: '昵称',
        name: 'name',
        placeholder: '请输入昵称'
      },
      {
        label: '个人简介',
        name: 'userDesc',
        placeholder: '请输入个人简介'
      }
    ],
    files: [],
    showTopTips: false,
    errorMsg: '输入错误'
  },
  onLoad: function(options) {
    app.getUserInfo().then(userInfo => {
      let files = [];
      userInfo.photo && files.push(userInfo.photo);
      userInfo.photo1 && files.push(userInfo.photo1);
      userInfo.photo2 && files.push(userInfo.photo2);

      let formItems = this.data.formItems;
      formItems[0].value = userInfo.name;
      formItems[1].value = userInfo.userDesc || '';
      this.setData({
        userInfo,
        files,
        formItems
      });
    });
  },
  onNavBack() {
    // 返回
    // wx.navigateBack();
    wx.redirectTo({
      url: `/pages/personalPage/personalPage`
    });
  },
  changeImg(e) {
    let order = e.currentTarget.id;
    this.uploadImg(order);
  },
  addImg() {
    this.uploadImg();
  },
  uploadImg(order) {
    let self = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        var tempFilePaths = res.tempFilePaths;
        wx.uploadFile({
          url: config.service.uploadFileUrl,
          filePath: tempFilePaths[0],
          name: 'file',
          formData: {},
          success: function(res) {
            let logo = JSON.parse(res.data).data.path;
            let files = self.data.files;
            if (order) {
              files[order] = logo;
            } else {
              files.push(logo);
            }
            self.setData({
              files
            });
          }
        });
      }
    });
  },
  validateData(fields, v) {
    let result = [];
    let msgs = [];

    fields.forEach(field => {
      if (field == 'name') {
        if (!v.name) {
          result.push('name');
          msgs.push('请输入姓名');
        }
        if (v.name.length > 10) {
          result.push('name');
          msgs.push('姓名不能超过10个字符');
        }
      }
      if (field == 'userDesc') {
        if (v.userDesc.length > 30) {
          result.push('userDesc');
          msgs.push('个人简介不能超过30个字符');
        }
      }
    });

    this.showError(result, msgs[0]);
    return result.length == 0;
  },
  showError(field, msg) {
    field = [].concat(field);
    let formItems = this.data.formItems;
    formItems.forEach(v => {
      if (field.includes(v.name)) {
        v.warn = true;
      } else {
        v.warn = false;
      }
    });

    if (field.length > 0) {
      var that = this;
      this.setData({
        showTopTips: true,
        errorMsg: msg || '输入错误',
        formItems
      });
      setTimeout(function() {
        that.setData({
          showTopTips: false
        });
      }, 2000);
    } else {
      // this.setData({
      //     formItems
      // });
    }
  },
  delPhoto(e) {
    let self = this;
    let index = e.currentTarget.dataset.index;
    wx.showModal({
      content: '确认删除吗？',
      confirmText: '确定',
      cancelText: '取消',
      success: function(res) {
        if (res.confirm) {
          let files = self.data.files;
          files.splice(index, 1);
          self.setData({
            files
          });
        }
      }
    });
  },
  formSubmit(e) {
    let self = this;
    let files = this.data.files;
    let formData = e.detail.value;
    let data = {
      id: self.data.userInfo.id,
      name: formData.name,
      userDesc: formData.userDesc
    };

    files &&
      files.map((item, index) => {
        if (index === 0) {
          data[`photo`] = item;
        } else {
          data[`photo${index}`] = item;
        }
      });
    let isPass = this.validateData(['name', 'userDesc'], data);
    if (!isPass) return;
    qcloud.request({
      url: config.service.updateUserAvatarInfoUrl,
      data,
      success: res => {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
        app.refreshUserInfo(() => {
          // wx.navigateBack();
          wx.redirectTo({
            url: `/pages/personalPage/personalPage`
          });
        });
      }
    });
  }
});
